import { ElMessage } from 'element-plus';
import { accessTokenKey, clearTokens, feature, getAPI } from '/@/utils/axios-utils';
import { SysAuthApi } from '/@/api-services/api';
import { NextLoading } from '/@/utils/loading';
import { saveLoginInfo, AppSessionInfo } from '/@/stores/baseInfo';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { sm2 } from 'sm-crypto-v2';
import { Local, Session } from '/@/utils/storage';

// 登录 / 保存token / 跳转到主界面
export const doLogin = async (ruleForm: any, route: any, router: any): Promise<boolean> => {
	// SM2加密密码
	// const keys = SM2.generateKeyPair();
	const publicKey = window.__env__.VITE_SM_PUBLIC_KEY;
	const password = sm2.doEncrypt(ruleForm.password, publicKey, 1);
	ruleForm.account = ruleForm.account.trim().toLowerCase(); // 登录账号不区分大小写

	const [err, res] = await feature(getAPI(SysAuthApi).apiSysAuthLoginPost({ ...ruleForm, password: password }));
	if (err) {
		return new Promise((resolve) => resolve(false));
	}
	if (res.data.result?.accessToken == undefined) {
		ElMessage.error('登录失败，请检查账号！');
		return new Promise((resolve) => resolve(false));
	}
	// 登录成功,缓存登录表单
	AppSessionInfo.setcurrentPasswordIsStrong(ruleForm.password);
	saveLoginInfo(ruleForm);
	await saveTokenAndInitRoutes(res.data.result?.accessToken, route, router,res.data.result?.accessTokenWCF);
	return new Promise((resolve) => resolve(true));
};

// 保存Token并初始化路由
export const saveTokenAndInitRoutes = async (accessToken: string | any, route: any, router: any,accessTokenWCF:string | any) => {
	Local.set(accessTokenKey, accessToken);
	// Local.set(refreshAccessTokenKey, refreshAccessToken);
	Session.set('token', accessToken);

	Local.set('access-token-wcf', accessTokenWCF);

	// 添加完动态路由再进行router跳转，否则可能报错 No match found for location with path "/"
	const isNoPower = await initBackEndControlRoutes();
	signInSuccess(isNoPower, route, router);
};

// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined, route: any, router: any) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		clearTokens(); // 清空Token缓存
	} else {
		// 登录成功，跳到转首页 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}

		// 初始化登录成功时间问候语
		//let currentTimeInfo = formatAxis(new Date());
		// 登录成功提示
		//const signInText = '登录成功'; // t('message.signInText');
		//ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
};
